<template>
  <div class="chewei">
    <div class="cheleft">
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div class="cheweiming">
          <p>车位名：</p>
          <el-input
            placeholder="请输入车位名"
            v-model="ruleForm.parkname"
          ></el-input>
        </div>
        <div class="cheweiming">
          <p>车位金额:</p>
          <el-input
            placeholder="请输入车位金额"
            v-model="ruleForm.parkpay"
          ></el-input>
        </div>
        <div class="cheweiming">
          <p>车位类型:</p>
          <el-select
            class="cheleixing"
            v-model="ruleForm.parktype"
            placeholder="请选择车位类型"
          >
            <el-option label="地上" :value="1"></el-option>
            <el-option label="地下" :value="2"></el-option>
          </el-select>
        </div>
        <div class="cheweiming">
          <p>车位状态:</p>
          <el-select
            class="cheleixing"
            v-model="ruleForm.parkstatus"
            placeholder="请选择车位状态"
          >
            <el-option label="已有车" :value="1"></el-option>
            <el-option label="未有车" :value="2"></el-option>
          </el-select>
        </div>

        <el-form-item class="anniuk">
          <el-button
            type="primary"
            class="chaxunan"
            @click="submitForm('ruleForm')"
            ><i class="el-icon-zoom-in"></i>查询</el-button
          >
          <el-button class="chaxunan" type="primary" @click="resetForm"
            ><i class="el-icon-edit"></i>重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="cheyou">
      <div class="cheti">
        <h2>车位列表</h2>
        <el-button type="success" @click="dialogFormVisible = true"
          ><i class="el-icon-plus"></i>新增</el-button
        >
      </div>
      <div class="cheneizhu" style="text-align: center">
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column
            type="index"
            width="80px"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="parkname"
            sortable
            label="车位名称"
            width="180px"
          >
          </el-table-column>
          <el-table-column
            prop="parkpay"
            sortable
            label="车位余额"
            width="180px"
          >
          </el-table-column>
          <el-table-column prop="parktype" label="车位类型">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.parktype"
                :active-value="1"
                :inactive-value="2"
                active-text="地下"
                inactive-text="地上"
                @change="dixia(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="parkstatus" label="车位状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.parkstatus"
                :active-value="1"
                :inactive-value="2"
                active-text="已有车"
                inactive-text="未有车"
                @change="dixia(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" width="270px">
            <template slot-scope="scope">
              <el-button
                @click="fenbei(scope.$index, scope.row)"
                type="info"
                plain
                :disabled="scope.row.parkstatus === 1"
                ><i class="el-icon-share"></i>分配车位</el-button
              >
              <el-button
                @click="handleEdit(scope.$index, scope.row)"
                style="color: rgb(8, 132, 221)"
                plain
                ><i class="el-icon-edit"></i>编辑</el-button
              >
              <el-button
                @click="handleDelete(scope.$index, scope.row)"
                type="danger"
                plain
                style="border: 1px solid red"
                ><i class="el-icon-delete"></i>移除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="block" style="float: right; margin: 30px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currPage"
          :page-sizes="[9, 20, 30, 40]"
          :page-size="pageNum"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <el-dialog title="新增车位" :visible.sync="dialogFormVisible">
        <el-form :model="form" style="width 300px;">
          <el-form-item label="车位名称：" :label-width="formLabelWidth">
            <el-input v-model="form.parkname" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="车位金额：" :label-width="formLabelWidth">
            <el-input v-model="form.parkpay" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="车位类型：" :label-width="formLabelWidth">
            <el-select
              style="width: 684px"
              v-model="form.parktype"
              placeholder="请选择"
            >
              <el-option label="地上" :value="2"></el-option>
              <el-option label="地下" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="车位状态：" :label-width="formLabelWidth">
            <el-select
              style="width: 684px"
              v-model="form.parkstatus"
              placeholder="请选择"
            >
              <el-option label="已有车" :value="1"></el-option>
              <el-option label="未有车" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogFormVisible = false"
            >取 消</el-button
          >
          <el-button type="primary" @click="tijiao">提交</el-button>
          <el-button type="primary" @click="chongzhi">重置</el-button>
        </div>
      </el-dialog>
      <el-dialog title="车位修改" :visible.sync="dialogTableVisible">
        <el-form :model="formm" style="width 300px;">
          <el-form-item label="车位名称：" :label-width="formLabelWidth">
            <el-input v-model="formm.parkname" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="车位金额：" :label-width="formLabelWidth">
            <el-input v-model="formm.parkpay" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="车位类型：" :label-width="formLabelWidth">
            <el-select
              style="width: 684px"
              v-model="formm.parktype"
              placeholder="请选择"
            >
              <el-option label="地上" :value="2"></el-option>
              <el-option label="地下" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="车位状态：" :label-width="formLabelWidth">
            <el-select
              style="width: 684px"
              v-model="form.parkstatus"
              placeholder="请选择"
            >
              <el-option label="已有车" :value="1"></el-option>
              <el-option label="未有车" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogTableVisible = false"
            >取 消</el-button
          >
          <el-button type="primary" @click="bianjiao">提交</el-button>
          <el-button type="primary" @click="chongzhi">重置</el-button>
        </div>
      </el-dialog>

      <el-drawer
        title="车位分配!"
        :visible.sync="table"
        direction="ltr"
        size="50%"
      >
        <!-- 1. 新增用户选择表格的选中事件和ref -->
        <el-table 
          :data="gridData" 
          @selection-change="handleSelectionChange" 
          ref="xvanzhong"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column
            type="index"
            width="80px"
            label="序号"
          ></el-table-column>
          <el-table-column
            property="username"
            label="用户账号"
            width="150"
          ></el-table-column>
          <el-table-column
            property="homeaddress"
            label="家庭住址"
          ></el-table-column>
          <el-table-column property="type" label="类型">
            <template slot-scope="scope">
              {{ scope.row.type == 2 ? "普通用户" : "管理员" }}
            </template>
          </el-table-column>
          <el-table-column
            property="parkname"
            label="车位"
            width="200"
          ></el-table-column>
        </el-table>
        <div
          class="block"
          style="margin: 30px 30px 30px 30px; text-align: right"
        >
          <el-pagination
            @size-change="pei"
            @current-change="peipei"
            :current-page="currPagee"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageNumm"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totall"
          >
          </el-pagination>
        </div>
        <div class="morenan">
          <el-button @click="quxiao" class="morenak">取消</el-button>
          <el-button class="morenak" @click="quedi" type="primary"
            >确定</el-button
          >
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      table: false,
      loading: false,
      gridData: [],
      dialogTableVisible: false,
      formLabelWidth: "120px",
      dialogFormVisible: false,
      ruleForm: {
        parkname: "",
        parkpay: "",
        parktype: "",
        parkstatus: "",
        token: "",
      },
      form: {
        parkname: "",
        parkpay: "",
        parktype: "",
        parkstatus: "",
        token: "",
      },
      formm: {
        parkname: "",
        parkpay: "",
        parktype: "",
        parkstatus: "",
        u_id: "",
        token: "",
      },
      formmm: {
        u_id: "", // 存储当前待分配的车位ID
        parkname: "",
        parkpay: "",
        parktype: "",
        parkstatus: "",
        token: "",
      },
      // 2. 新增：存储选中的用户（和第一份代码一致）
      selectedRow: "",
      pageNum: 9,
      currPage: 1,
      pageNumm: 10,
      currPagee: 1,
      tableData: [],
      total: 0,
      totall: 0,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    quxiao() {
      this.table = false;
      // 取消时清空选中的用户
      this.selectedRow = "";
      this.$refs.xvanzhong && this.$refs.xvanzhong.clearSelection();
    },

    // 3. 核心修改：重写quedi方法，融入第一份代码的双接口分配逻辑
    async quedi() {
      await this.$confirm("确定分配该车位？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 校验是否选中用户
          if (!this.selectedRow) {
            this.$message({
              message: "请选择用户",
              type: "warning",
            });
            return;
          }

          try {
            // 3.1 调用第一份代码的「用户分配车位接口」
            await this.$axios.post("/users/updateParkStatus", {
              u_id: this.selectedRow.id, // 选中用户的ID
              parkId: this.formmm.u_id, // 当前待分配的车位ID
              parkname: this.formmm.parkname, // 车位名称
              parkstatus: this.selectedRow.parkstatus, // 用户当前车位状态
              token: localStorage.getItem("token"), // 从localStorage拿token（和第一份一致）
            });

            // 3.2 调用原有「车位状态更新接口」（保持逻辑不变，仅替换硬编码token）
            const assignedParkData = {
              id: this.formmm.u_id,
              parkname: this.formmm.parkname,
              parkpay: this.formmm.parkpay,
              parktype: this.formmm.parktype,
              parkstatus: 1, // 车位改为「已有车」
            };
            await this.getbian(assignedParkData);

            // 分配成功提示
            this.$message({
              type: "success",
              message: "分配成功!",
            });
            this.table = false;
            this.getList(); // 刷新车位列表
            this.getpei(); // 刷新用户列表
          } catch (error) {
            console.error("分配失败", error);
            this.$message({
              message: "分配失败，请重试",
              type: "error",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消分配",
          });
        });
    },

    pei(val) {
      console.log(`每页 ${val} 条`);
      this.pageNumm = val;
      this.getpei();
    },
    peipei(val) {
      console.log(`当前页: ${val}`);
      this.currPagee = val;
      this.getpei();
    },
    async getpei() {
      this.loading = true;
      try {
        let res = await this.$axios.get(
          `http://community.byesame.com/users/getUsersData?currPage=${
            this.currPagee - 1
          }&pageNum=${this.pageNumm}`
        );
        this.gridData = res.data.data;
        this.totall = res.data.total;
      } finally {
        this.loading = false;
      }
    },

    fenbei(index, row) {
      console.log(index, row);
      // 存储当前待分配的车位数据
      this.formmm.u_id = row.id;
      this.formmm.parkname = row.parkname;
      this.formmm.parkpay = row.parkpay;
      this.formmm.parktype = row.parktype;
      this.formmm.parkstatus = row.parkstatus;
      // 从localStorage拿token（替换原硬编码）
      this.formmm.token = localStorage.getItem("token");

      this.table = true;
      this.getpei();
      // 打开抽屉时清空之前的选中
      this.selectedRow = "";
    },
    // 4. 新增：处理用户选择（和第一份代码一致，限制只能选一个）
    handleSelectionChange(val) {
      if (val.length > 1) {
        this.$refs.xvanzhong.clearSelection();
        this.$refs.xvanzhong.toggleRowSelection(val[val.length - 1], true);
      } else if (val.length == 1) {
        this.selectedRow = val[0];
      } else {
        this.selectedRow = "";
      }
    },
    chongzhi() {
      this.form.parkname = "";
      this.form.parkpay = "";
      this.form.parktype = "";
      this.form.parkstatus = "";
      this.formm.parkname = "";
      this.formm.parkpay = "";
      this.formm.parktype = "";
      this.formm.parkstatus = "";
    },
    tijiao() {
      this.getti();
    },
    async getti() {
      // 替换硬编码token为localStorage
      this.form.token = localStorage.getItem("token");
      let res = await this.$axios.post(
        `http://community.byesame.com/parking/addParkData`,
        this.form
      );
      console.log("添加成功", res);
      this.$message({
        message: "添加成功",
        type: "success",
      });
      this.dialogFormVisible = false;
      this.chongzhi();
      this.getList();
    },
    dixia(index) {
      console.log(index);
      this.getbian(index);
    },
    // 5. 修改：getbian方法替换硬编码token
    async getbian(parkData) {
      try {
        const { id: u_id, parkname, parkpay, parktype, parkstatus } = parkData;

        const res = await this.$axios.post(
          "http://community.byesame.com/parking/editParkData",
          {
            u_id,
            parkname,
            parkpay,
            parktype,
            parkstatus,
            token: localStorage.getItem("token"), // 替换硬编码token
          }
        );

        console.log("更新成功，接口返回数据：", res);
        this.$message.success("车位信息更新成功！");
        this.getList();
      } catch (error) {
        console.error("更新车位失败，错误信息：", error);
        this.$message.error("更新失败，请稍后重试！");
      }
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = val;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currPage = val - 1;
      this.getList();
    },
    bianjiao() {
      // 替换硬编码token
      this.formm.token = localStorage.getItem("token");
      this.getxiu();
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogTableVisible = true;
      this.formm.parkname = row.parkname;
      this.formm.parkpay = row.parkpay;
      this.formm.parktype = row.parktype;
      this.formm.parkstatus = row.parkstatus;
      this.formm.u_id = row.id;
    },
    async getxiu() {
      let res = await this.$axios.post(
        `http://community.byesame.com/parking/editParkData`,
        this.formm
      );
      console.log("修改成功", res);
      this.$message({
        message: "修改成功",
        type: "success",
      });
      this.getList();
      this.dialogTableVisible = false;
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getdel(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 6. 修改：getdel方法替换硬编码token
    async getdel(id) {
      let res = await this.$axios.get(
        `http://community.byesame.com/parking/delParkData?id=${id}&token=${localStorage.getItem("token")}`
      );
      console.log("删除成功", res);
      this.getList();
    },
    async getList() {
      let res = await this.$axios.get(
        `http://community.byesame.com/parking/getParkData?parkname=&parkpay=&parktype=&parkstatus=&currPage=${
          this.currPage - 1
        }&pageNum=${this.pageNum}`
      );
      console.log(res);
      this.tableData = res.data.data;
      this.total = res.data.total;
    },
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            const res = await this.$axios.get(
              `http://community.byesame.com/parking/getParkData?parkname=${
                this.ruleForm.parkname
              }&parkpay=${this.ruleForm.parkpay}&parktype=${
                this.ruleForm.parktype
              }&parkstatus=${this.ruleForm.parkstatus}&currPage=${
                this.currPage - 1
              }&pageNum=${this.pageNum}`
            );

            this.tableData = res.data.data;
            console.log(this.tableData);

            this.$message.success("查询成功");
          } catch (err) {
            this.$message.error("查询失败，请重试");
            console.error("查询接口错误：", err);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm() {
      this.ruleForm.parkname = "";
      this.ruleForm.parktype = "";
      this.ruleForm.parkpay = "";
      this.ruleForm.parkstatus = "";
      this.getList();
    },
  },
};
</script>

<style scoped>
.cheleft {
  width: 30%;
}
.cheweiming {
  margin-top: 1.25rem;
}
.cheweiming p {
  margin-bottom: 0.625rem;
}
.cheleixing {
  width: 30.25rem;
}
.anniuk {
  margin-top: 1.875rem;
}
.chaxunan {
  padding: 0.5625rem 3.75rem;
  margin-right: 0.625rem;
}
.cheyou {
  width: 65%;
  margin-left: 1.875rem;
}
.chewei {
  display: flex;
}
.cheti {
  display: flex;
  justify-content: space-between;
  margin-right: 1.875rem;
}
.cheneizhu {
  margin-top: 1.875rem;
}
.morenan {
  display: flex;
  justify-content: space-evenly;
}
.morenak {
  padding: 0.5625rem 5rem;
}
</style>